# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA


from sql_parse import DataDict, Field, Table


class Inspector(object):

    def __init__(self):
        self.tables = ()

    def explore(self, connection):
        cursor = connection.cursor()
        cursor.execute('select name from sqlite_master ' +
        ' where type=\'table\';')
        self.tables = tuple(x[0] for x in cursor.fetchall()
                     if not x[0].startswith('sqlite_'))
        fields = {}
        for name in self.tables:
            cursor.execute('PRAGMA table_info(\'' + name + '\')')
            fields[name] = []
            for field in cursor.fetchall():
                ftype = field[2]
                fields[name].append(Field(name=field[1], type=field[2],
                length=0, not_null=field[3], default=field[4], pk=field[5]))
            fields[name] = tuple(fields[name])
        self.fields = fields

    def get_data_dict(self):
        dd = DataDict()
        for t in self.tables:
            tbl = Table()
            f = dict((f.name, f) for f in self.fields[t])
            tbl.fields = f
            dd[t] = tbl
        return dd
